package demo.service;

import java.util.ArrayList;
import java.util.List;

import util.FloatViewManager;
import util.MLog;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.AsyncTask;
import android.os.IBinder;

public class FloatingService extends Service {

	public static final String ACTION_HOME_DISPLAY = "demo.service.floating.ACTION_HOME_DIAPLY";
	public static final String ACTION_HOME_HIDDEN = "demo.service.floating.ACTION_HOME_HIDDEN";
	public static final String EXTRA_DISPLAY = "displaybean";

	private FloatingService mServices = null;
	private ListenHomeTask mListenTask = null;
	private BroadcastReceiver mHomeReceview = null;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		
		MLog.i(getClass(), "onCreate()");
		mServices = this;
		mListenTask = new ListenHomeTask();
		mListenTask.execute();
		mHomeReceview = new HomeReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(ACTION_HOME_DISPLAY);
		filter.addAction(ACTION_HOME_HIDDEN);
		registerReceiver(mHomeReceview, filter);
	}

	@Override
	public void onDestroy() {
		MLog.i(getClass(), "onDestroy()");
		mListenTask.stopTask();
		mListenTask =  null;
		unregisterReceiver(mHomeReceview);
		super.onDestroy();
	}

	class HomeReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
//			FloatViewManager manager = FloatViewManager.getInstance(context);
			if (ACTION_HOME_DISPLAY.equals(action)) {
				if(intent != null){					
					FloatViewManager.showDisplayView();
				}
			} else if (ACTION_HOME_HIDDEN.equals(action)) {
				FloatViewManager.removeDisplayView();
			}
		}

	}

	class ListenHomeTask extends AsyncTask<Object, Integer, Boolean> {
		private boolean stop = false;
		private List<String> homes = null;
		private boolean lastIsHome = false;

		public ListenHomeTask() {
			stop = false;
			homes = getHomes();
			lastIsHome = isHome();
			sendBroadcast(lastIsHome);
		}

		public void stopTask() {
			stop = true;
		}

		private void sendBroadcast(boolean isHome) {
			if (!isHome) {
				MLog.e(getClass(), "home displayed");
				mServices.sendBroadcast(new Intent((ACTION_HOME_DISPLAY)));
			} else {
				MLog.e(getClass(), "home hidden");
				mServices.sendBroadcast(new Intent((ACTION_HOME_HIDDEN)));
			}
		}

		@Override
		protected Boolean doInBackground(Object... params) {
			while (!stop) {
				boolean isHome = isHome();
				// when the current status is diffrent with the last status .
				// send a broadcast
				if (lastIsHome != isHome) {
					sendBroadcast(isHome);
					lastIsHome = isHome;
				}
				try {
					Thread.sleep(200);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			return true;
		}

		public boolean isHome() {
			ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
			List<RunningTaskInfo> rti = mActivityManager
					.getRunningTasks(Integer.MAX_VALUE);
			return homes.contains(rti.get(0).topActivity.getPackageName());
		}

		private List<String> getHomes() {
			List<String> packages = new ArrayList<String>();
			PackageManager packageManager = mServices.getPackageManager();
			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.addCategory(Intent.CATEGORY_HOME);
			List<ResolveInfo> resolveInfo = packageManager
					.queryIntentActivities(intent,
							PackageManager.MATCH_DEFAULT_ONLY);
			for (ResolveInfo info : resolveInfo) {
				packages.add(info.activityInfo.packageName);
			}
			return packages;
		}
	}

}
